<?php
class Export{
    public $objPHPExcel;
    public $fileName;
    public $fileType;

    public static $cellArray = ['A', 'B', 'C', 'D', 'E', 'F', 'H', 'I', 'G', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];

    public function __construct($filename, $type = "xls")
    {
        $this->fileName = $filename;
        $this->fileType = $type;
        //yii 的导入
        Yii::import('ext.PHPExcel.Classes.*');
        $this->setObjPHPExcel();
    }

    public function setObjPHPExcel()
    {
        $this->objPHPExcel = new PHPExcel();
    }

    public function getCoordinate($num, $i)
    {
        $n = ($num % 25);
        $l = self::$cellArray[ $n ];
        return $l . ($i + 1);
    }

    //赋值
    public function setData($body)
    {
        foreach ($body as $i => $data) {
            $object = $this->objPHPExcel->setActiveSheetIndex(0);
            foreach ($data as $k => $v) {
                $cellKey = $this->getCoordinate($k, $i);
                $object->setCellValue($cellKey, "".$v);
            }
        }
    }

    //实现下载
    public function finalize()
    {
        header('Content-Type: application/vnd.ms-excel');
        header(sprintf('Content-Disposition: attachment;filename=%s.%s', $this->fileName, $this->fileType));
        header('Cache-Control: max-age=0');
        $objWriter = PHPExcel_IOFactory::createWriter($this->objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        Yii::app()->end();
        spl_autoload_register(['YiiBase', 'autoload']);
        exit();
    }
}